package swim.servlets;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;
import swim.sessionbean.AccessoRemote;
import javax.rmi.PortableRemoteObject;
import java.util.Hashtable;
import java.util.Properties;

public class ServletFunctions {
	
	static private Context inizializzazione() throws Exception{
		Properties abc = new Properties();
		abc.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		abc.put(Context.PROVIDER_URL, "jnp://localhost:1099");
		
		return new InitialContext(abc);
		
	}
	
	public final static String ACCESS_REMOTE_ATTRIBUTE = "accesso_Remoto" ; 
	
	static private AccessoRemote getAccessoRemote() throws Exception {
		AccessoRemote accesso = (AccessoRemote)inizializzazione().lookup("AccessoRemote");
		return accesso;
		
	}

	static public AccessoRemote getAccessoRemote(HttpServletRequest request) throws SwimWebException {
		AccessoRemote remote = (AccessoRemote)request.getSession().getAttribute("ACCESS_REMOTE_ATTRIBUTE");
		if (remote == null){
			throw new SwimWebException("Login non effettuato o sessione scaduta");
		}
		return remote;
	}
	
	static public AccessoRemote nuovoAccessoRemote(HttpServletRequest request) throws Exception {
		AccessoRemote remote = null;
		try{
			remote = getAccessoRemote();
			request.getSession().setAttribute("ACCESS_REMOTE_ATTRIBUTE", remote);
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return remote;
	}
	
	
	
}
